package com.sgcc.activiti.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.sgcc.activiti.domain.*;
import com.sgcc.activiti.service.IOInterfaceIndexService;
import com.sgcc.activiti.service.IProcessService;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.text.UUID;
import com.sgcc.common.core.utils.FastJsonUtil;
import com.sgcc.common.core.utils.HttpClientUtil;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.core.web.page.PageDomain;
import com.sgcc.common.core.web.page.TableDataInfo;
import com.sgcc.system.api.RemoteAreaService;
import com.sgcc.system.api.domain.SysArea;
import com.sgcc.activiti.service.IOContentAppSchemaService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.util.CollectionUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.sgcc.activiti.mapper.OContentAppMapper;
import com.sgcc.activiti.service.IOContentAppService;
import org.springframework.util.CollectionUtils;

/**
 * 资讯内容管理网上国网Service业务层处理
 *
 * @author sgcc
 * @date 2021-03-31
 */
@Service
public class OContentAppServiceImpl implements IOContentAppService {
    @Value("${isTest}")
    private Boolean isTest;

    @Autowired
    private OContentAppMapper oContentAppMapper;

    @Autowired
    private RemoteAreaService remoteAreaService;

    @Autowired
    private IOInterfaceIndexService interfaceIndexService;

    @Autowired
    private IOContentAppSchemaService oContentAppSchemaService;

    @Autowired
    private IProcessService processService;

    /**
     * 查询资讯内容管理网上国网
     *
     * @param id 资讯内容管理网上国网ID
     * @return 资讯内容管理网上国网
     */
    @Override
    public OContentApp selectOContentAppById(String id) {
        return oContentAppMapper.selectOContentAppById(id);
    }

    /**
     * 查询资讯内容管理网上国网列表
     *
     * @param oContentApp 资讯内容管理网上国网
     * @return 资讯内容管理网上国网
     */
    @Override
    public List<OContentApp> selectOContentAppList(OContentApp oContentApp) {
        return oContentAppMapper.selectOContentAppList(oContentApp);
    }

    /**
     * 新增资讯内容管理网上国网
     *
     * @param oContentApp 资讯内容管理网上国网
     * @return 结果
     */
    @Override
    public OContentApp insertOContentApp(OContentApp oContentApp) {
        if (null == oContentApp.getId()) {
            oContentApp.setId(UUID.randomUUID().toString().replaceAll("-", ""));
//            oContentApp.setNewId(UUID.randomUUID().toString().replaceAll("-", ""));
        }
        int i = oContentAppMapper.insertOContentApp(oContentApp);
        if (i > 0) {
            return oContentApp;
        } else {
            return null;
        }
    }

    /**
     * 修改资讯内容管理网上国网
     *
     * @param oContentApp 资讯内容管理网上国网
     * @return 结果
     */
    @Override
    public int updateOContentApp(OContentApp oContentApp) {
        return oContentAppMapper.updateOContentApp(oContentApp);
    }

    /**
     * 批量删除资讯内容管理网上国网
     *
     * @param ids 需要删除的资讯内容管理网上国网ID
     * @return 结果
     */
    @Override
    public int deleteOContentAppByIds(String[] ids) {
        return oContentAppMapper.deleteOContentAppByIds(ids);
    }

    /**
     * 删除资讯内容管理网上国网信息
     *
     * @param id 资讯内容管理网上国网ID
     * @return 结果
     */
    @Override
    public int deleteOContentAppById(String id) {
        return oContentAppMapper.deleteOContentAppById(id);
    }

    @Override
    public Map<String, Object> findPageInfo(PageDomain<OContentApp> pageDomain, OContentApp oContentApp) throws Exception {
        //入参：发布状态 1已上架2已下架
        String state = oContentApp.getAdvissueState();
        int pageNo = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();
        //入参：数据起始位置
        int iDisplayStart = pageNo;
        //入参：数据长度
        int iDisplayLength = pageSize;
        int resultCode = 0;
        String message = "";


        if (isTest) {
            resultCode = 1;
            //远程调用资讯内容列表查询接口,需求未提供调用接口，暂时使用假数据。
            String rpcResultStr = "{\n" +
                    "    \"code\": 1,\n" +
                    "    \"message\": \"成功\",\n" +
                    "    \"data\": {\n" +
                    "        \"iTotalRecords\": \"3\",\n" +
                    "        \"contentList\": [\n" +
                    "            {\n" +
                    "                \"contentId\": \"d735a63f148448529732e708157dd197\",\n" +
                    "                \"contentTitle\": \"大转盘活动004\",\n" +
                    "                \"contentScene\": \"1\",\n" +
                    "                \"advIssueState\": \"2\",\n" +
                    "                \"contentDetails\": \"资讯简述1\",\n" +
                    "                \"releaseScope\": \"350101\",\n" +
                    "                \"pulishType\": \"最新\",\n" +
                    "                \"releaseTime\": \"2019-04-24 00:00:00\"\n" +
                    "            },\n" +
                    "            {\n" +
                    "                \"contentId\": \"f43a7fb827ee49cebfa482f5bca0f35a\",\n" +
                    "                \"contentTitle\": \"视频05\",\n" +
                    "                \"contentScene\": \"1\",\n" +
                    "                \"advIssueState\": \"1\",\n" +
                    "                \"contentDetails\": \"资讯简述1-86-05\",\n" +
                    "                \"releaseScope\": \"350101\",\n" +
                    "                \"pulishType\": \"2\",\n" +
                    "                \"releaseTime\": \"2019-04-25 00:00:00\"\n" +
                    "            },\n" +
                    "            {\n" +
                    "                \"contentId\": \"a84fa40d-539e-457e-849a-6e355ce6a72f\",\n" +
                    "                \"contentTitle\": \"11\",\n" +
                    "                \"contentScene\": \"1\",\n" +
                    "                \"advIssueState\": \"1\",\n" +
                    "                \"contentDetails\": \"11\",\n" +
                    "                \"releaseScope\": \"350101\",\n" +
                    "                \"pulishType\": \"1\",\n" +
                    "                \"releaseTime\": \"2021-01-15 00:00:00\"\n" +
                    "            },\n" +
                    "            {\n" +
                    "                \"contentId\": \"1cbceb75dc84400ba298450adb053442\",\n" +
                    "                \"contentTitle\": \"资讯009\",\n" +
                    "                \"contentScene\": \"1\",\n" +
                    "                \"advIssueState\": \"1\",\n" +
                    "                \"contentDetails\": \"资讯简述32\",\n" +
                    "                \"releaseScope\": \"350101\",\n" +
                    "                \"pulishType\": \"12\",\n" +
                    "                \"releaseTime\": \"2019-04-25 00:00:00\"\n" +
                    "            }\n" +
                    "        ]\n" +
                    "    }\n" +
                    "}";
            if ("1".equals(state)) {
                rpcResultStr = "{\n" +
                        "    \"code\": 1,\n" +
                        "    \"message\": \"成功\",\n" +
                        "    \"data\": {\n" +
                        "        \"iTotalRecords\": \"3\",\n" +
                        "        \"contentList\": [\n" +
                        "            {\n" +
                        "                \"contentId\": \"f43a7fb827ee49cebfa482f5bca0f35a\",\n" +
                        "                \"contentTitle\": \"视频05\",\n" +
                        "                \"contentScene\": \"1\",\n" +
                        "                \"advIssueState\": \"1\",\n" +
                        "                \"contentDetails\": \"资讯简述1-86-05\",\n" +
                        "                \"releaseScope\": \"350101\",\n" +
                        "                \"pulishType\": \"2\",\n" +
                        "                \"releaseTime\": \"2019-04-25 00:00:00\"\n" +
                        "            },\n" +
                        "            {\n" +
                        "                \"contentId\": \"a84fa40d-539e-457e-849a-6e355ce6a72f\",\n" +
                        "                \"contentTitle\": \"11\",\n" +
                        "                \"contentScene\": \"1\",\n" +
                        "                \"advIssueState\": \"1\",\n" +
                        "                \"contentDetails\": \"11\",\n" +
                        "                \"releaseScope\": \"350101\",\n" +
                        "                \"pulishType\": \"1\",\n" +
                        "                \"releaseTime\": \"2021-01-15 00:00:00\"\n" +
                        "            },\n" +
                        "            {\n" +
                        "                \"contentId\": \"1cbceb75dc84400ba298450adb053442\",\n" +
                        "                \"contentTitle\": \"资讯009\",\n" +
                        "                \"contentScene\": \"1\",\n" +
                        "                \"advIssueState\": \"1\",\n" +
                        "                \"contentDetails\": \"资讯简述32\",\n" +
                        "                \"releaseScope\": \"350101\",\n" +
                        "                \"pulishType\": \"12\",\n" +
                        "                \"releaseTime\": \"2019-04-25 00:00:00\"\n" +
                        "            }\n" +
                        "        ]\n" +
                        "    }\n" +
                        "}";
            } else if ("2".equals(state)) {
                rpcResultStr = "{\n" +
                        "    \"code\": 1,\n" +
                        "    \"message\": \"成功\",\n" +
                        "    \"data\": {\n" +
                        "        \"iTotalRecords\": \"1\",\n" +
                        "        \"contentList\": [\n" +
                        "            {\n" +
                        "                \"contentId\": \"d735a63f148448529732e708157dd197\",\n" +
                        "                \"contentTitle\": \"大转盘活动004\",\n" +
                        "                \"contentScene\": \"1\",\n" +
                        "                \"advIssueState\": \"2\",\n" +
                        "                \"contentDetails\": \"资讯简述1\",\n" +
                        "                \"releaseScope\": \"350101\",\n" +
                        "                \"pulishType\": \"最新\",\n" +
                        "                \"releaseTime\": \"2019-04-24 00:00:00\"\n" +
                        "            }\n" +
                        "        ]\n" +
                        "    }\n" +
                        "}";
            }
            Map<String, Object> map = new HashMap<String, Object>(16);
            map.put("total", 0);
            map.put("rows", null);
            if (resultCode == 1) {
                OContentAppResult oContentAppResult = FastJsonUtil.toBean(rpcResultStr, OContentAppResult.class);
                int oContentAppResultCode = oContentAppResult.getCode();
                if (oContentAppResultCode == 1) {
                    JSONObject data = (JSONObject) oContentAppResult.getData();
                    OContentAppListResult oContentAppListResult = data.toJavaObject(OContentAppListResult.class);
                    //总条数
                    Long totalRecords = 0L;
                    if (oContentAppListResult.getiTotalRecords() != null && !"".equals(oContentAppListResult.getiTotalRecords())) {
                        totalRecords = Long.valueOf(oContentAppListResult.getiTotalRecords());
                    }
                    map.put("total", totalRecords);
                    //列表数据
                    List<OContentApp> advList = oContentAppListResult.getContentList();
                    for (int i = 0; i < advList.size(); i++) {
                        OContentApp old = oContentAppMapper.selectOcontentAppByNewId(advList.get(i).getContentId());
                        if (old != null) {
                            old.setPulishType(old.getPublishType());
                            old.setReleaseTime(advList.get(i).getReleaseTime());
                            old.setAdvissueState(advList.get(i).getAdvissueState());
                            old.setContentId(advList.get(i).getContentId());
                            advList.set(i, old);
                        }
                    }
//                    Set set = new HashSet();
//                    for (OContentApp item : advList) {
//                        set.add(item.getReleaseScope());
//                        //发布状态 1：已上架  2：已下架
//                        String advIssueState = item.getAdvissueState();
//                        switch (advIssueState) {
//                            case "1" :
//                                item.setAdvissueState("已上架");
//                                break;
//                            case "2" :
//                                item.setAdvissueState("已下架");
//                                break;
//                            default:
//                                break;
//                        }
//                    }
//                    List<String> orgList = Lists.newArrayList(set);
//                    List<SysArea> arealist = remoteAreaService.getArealistBycode(orgList);
//                    for (OContentApp item : advList) {
//                        for (SysArea area : arealist) {
//                            if (item.getReleaseScope() != null && item.getReleaseScope().equals(area.getCode())) {
//                                item.setReleaseScope(area.getName());
//                                break;
//                            }
//                        }
//                    }
                    map.put("rows", advList);
                }
            }
            return map;
        } else {


            // 接口地址维护表查询接口地址，通过接口地址编码
            // String rpcInterface = DictUtils.getDictValue("统一业务接口", "rpcInterface", "test");
            OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101114");
            if (null == oInterfaceIndex || null == oInterfaceIndex.getInterfaceAdress()) {
                throw new Exception("无法根据0101114获得接口");
            }

            String params = "";
            //构建参数
            /**
             * {
             "serviceCode":"0101114",
             "target":"35101",
             "source":"SGAPP",
             "data":{
             "releaseScope":"35101",
             "platformId":"35101",
             "iDisplayStart":"0",
             "iDisplayLength":"9",
             "advIssueState":"1"
             }
             * }
             */
            Map paramsData = new HashMap();
            paramsData.put("releaseScope", "350000");
            paramsData.put("platformId", "350000");
            paramsData.put("iDisplayStart", iDisplayStart);
            paramsData.put("advIssueState", state);
            paramsData.put("iDisplayLength", iDisplayLength);
            Map map = new HashMap();
            map.put("serviceCode", "0101114");
            map.put("source", "SGAPP");
            map.put("target", "35101");
            map.put("data", paramsData);
            params = FastJsonUtil.toJSONString(map);
            R<String> rpcResultStr = HttpClientUtil.sendJsonStr(oInterfaceIndex.getInterfaceAdress(), params);
            if (rpcResultStr.getCode() != 200) {
                throw new Exception(rpcResultStr.getMsg());
            }
            //解析返回值
            OContentAppResult oContentAppResult = FastJsonUtil.toBean(rpcResultStr.getData(), OContentAppResult.class);
            resultCode = oContentAppResult.getCode();
            message = oContentAppResult.getMessage();
            if (resultCode == 1) {
                JSONObject data = (JSONObject) oContentAppResult.getData();
                OContentAppListResult result = data.toJavaObject(OContentAppListResult.class);
                Map map11 = new HashMap(16);
                map11.put("total", result.getiTotalRecords());
                List<OContentApp> advList = result.getContentList();
                for (int i = 0; i < advList.size(); i++) {
                    OContentApp old = oContentAppMapper.selectOcontentAppByNewId(advList.get(i).getContentId());
                    if (old != null) {
                        old.setPulishType(old.getPublishType());
                        old.setReleaseTime(advList.get(i).getReleaseTime());
                        old.setAdvissueState(advList.get(i).getAdvissueState());
                        old.setContentId(advList.get(i).getContentId());
                        advList.set(i, old);
                    }
                }


//                Set set = new HashSet();
//                for (OContentApp item : advList) {
//                    set.add(item.getReleaseScope());
//                    //发布状态 1：已上架  2：已下架
//                    String advIssueState = item.getAdvissueState();
//                    switch (advIssueState) {
//                        case "1":
//                            item.setAdvissueState("已上架");
//                            break;
//                        case "2":
//                            item.setAdvissueState("已下架");
//                            break;
//                        default:
//                            break;
//                    }
//                }
//                List<String> orgList = Lists.newArrayList(set);
//                List<SysArea> arealist = remoteAreaService.getArealistBycode(orgList);
//                for (OContentApp item : advList) {
//                    for (SysArea area : arealist) {
//                        if (item.getReleaseScope() != null && item.getReleaseScope().equals(area.getCode())) {
//                            item.setReleaseScope(area.getName());
//                            break;
//                        }
//                    }
//                }
                map11.put("rows", advList);
                return map11;
            } else {
                throw new Exception("调用远程接口失败");
            }
        }
    }

    @Override
    public List<OContentApp> findAppList(OContentApp oContentApp) throws Exception {
        List<OContentApp> appList = oContentAppMapper.findAppList(oContentApp);
//        if(CollectionUtil.isNotEmpty(appList)){
//            for (OContentApp app:appList) {
//                //展示频道
//                List<TxtDto> sceneList = oContentAppSchemaService.sceneDta();
//                for (TxtDto txt:sceneList) {
//                    if(StringUtils.isNotBlank(app.getContentScene()) && app.getContentScene().equals(txt.getValue())){
//                        app.setContentScene(txt.getLabel());
//                        break;
//                    }
//                }
//                //维护类型
//                String serviceType = app.getServiceType();
//                if(StringUtils.isNotBlank(serviceType)){
//                    switch (serviceType){
//                        case "01":app.setServiceType("新增");break;
//                        case "02":app.setServiceType("变更");break;
//                        case "03":app.setServiceType("下架");break;
//                        default:app.setServiceType("");
//                    }
//                }
//                // 流程状态
//                String flowType = app.getFlowType();
//                if(StringUtils.isNotBlank(flowType)){
//                    switch (flowType){
//                        case "01":app.setFlowTypeName("待提交");break;
//                        case "02":app.setFlowTypeName("待审核");break;
//                        case "03":app.setFlowTypeName("待发布");break;
//                        case "04":app.setFlowTypeName("待反馈");break;
//                        case "05":app.setFlowTypeName("发布失败");break;
//                        case "06":app.setFlowTypeName("结束");break;
//                        case "07":app.setFlowTypeName("待提交-审核不通过");break;
//                        case "08":app.setFlowTypeName("终止");break;
//                        case "09":app.setFlowTypeName("结束-远程调用失败");break;
//                        case "10":app.setFlowTypeName("重新发布待反馈");break;
//                        case "11":app.setFlowTypeName("下架待反馈");break;
//                        default:app.setServiceType("");
//                    }
//                }
//            }
//
//        }
        if (!CollectionUtils.isEmpty(appList)) {
            appList.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        return appList;
    }

    @Override
    public OContentApp selectOContentAppByNewId(String newId) {
        return oContentAppMapper.selectOcontentAppByNewId(newId);
    }
}
